package com.test.filter;

import com.test.feign.OauthFeignService;
import com.test.properties.NotMatcherUrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.LinkedHashSet;

/**
 * 拦截器（请求路径不在配置文件的lhc:auth:shouldSkipUrls被拦截）
 *
 * @Author lhc
 * @Date 2021/8/16 10:14
 */
@Component
@Order(0)
@EnableConfigurationProperties(value = NotMatcherUrlProperties.class)
@Slf4j
public class AuthenticationFilter implements GlobalFilter {
    @Autowired
    private NotMatcherUrlProperties notMatcherUrlProperties;
    @Autowired
    private OauthFeignService oauthFeignService;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.过滤不需要认证的url
        String currentUrl = exchange.getRequest().getURI().getPath();
        if (shouldSkip(currentUrl)) {
            return chain.filter(exchange);
        }
        //2.从请求头解析token
        String authorizationValue = exchange.getRequest().getHeaders().getFirst("Authorization");
//        if (StringUtils.isBlank(authorizationValue)) {
//            log.warn("url请求头Authorization为空");
//            throw new RuntimeException("url请求头Authorization为空");
//        }
        //3.校验token
//        Map map = oauthFeignService.checkToken();


        //4.校验通过后，从token中获取的用户登录信息存储到请求头中


        return chain.filter(exchange);
    }


    private boolean shouldSkip(String currentUrl) {
        //spring-mvc的路径匹配器
        PathMatcher pathMatcher = new AntPathMatcher();
        LinkedHashSet<String> shouldSkipUrls = notMatcherUrlProperties.getShouldSkipUrls();
        for (String shouldSkipUrl : shouldSkipUrls) {
            if (pathMatcher.match(currentUrl, shouldSkipUrl)) {
                return true;
            }
        }
        return false;
    }


}